package com.cbc.ourgame.slideshowmaker.components.editor
{
	import assets.galleryscreen.GalleryChooserAsset;
	
	import com.cbc.ourgame.slideshowmaker.events.MeasurementEvent;
	import com.cbc.ourgame.slideshowmaker.model.datastructures.GalleryData;
	import com.ghostmonk.shapes.InnerShadowRectangle;
	
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	
	[Event (name="mouseWheel", type="flash.events.MouseEvent")]
	[Event (name="heightMeasurement", type="com.cbc.ourgame.slideshowmaker.events.MeasurementEvent")]
	
	public class GalleryChooser extends EventDispatcher
	{
		private var _view:GalleryChooserAsset;
		private var _galleryItems:Array;
		private var _mask:InnerShadowRectangle;
		private var _callback:Function;
		
		private var _maxY:Number;
		private var _minY:Number;
		private var _originHeight:Number;
		private var _countPostfix:String;
		
		public function get view():GalleryChooserAsset { return _view; }
		public function set countPostfix(value:String):void { _countPostfix = value; }
		
		public function GalleryChooser(view:GalleryChooserAsset, callback:Function)
		{
			_callback = callback;
			_mask = new InnerShadowRectangle(0, view.width + 10, view.height);
			_mask.x = view.x;
			_mask.y = view.y;
			_view = view;
			_view.mask = _mask;
			_view.hitarea.width = _mask.width;
			
			_maxY = _view.y;
			_originHeight = _view.height;
		}
		
		public function resetYPos():void
		{
			view.y = _maxY;
		}
		
		public function scroll(percent:Number):void
		{
			_view.y = int(-(_maxY - _minY) * percent + _maxY);
		}
		
		public function addGalleryItems(dataItems:Array):void
		{
			var col:int;
			var row:int;
			
			_galleryItems = [];
			for(var i:int = 0; i< dataItems.length; i++)
			{
				var item:GalleryItem = new GalleryItem(dataItems[i], onClick, _countPostfix);
				view.addChild(item);
				
				col = i % 2;
				row = Math.floor(i/2);
				
				item.x = (item.width + 5)*col;
				item.y = (item.height + 5)*row;
			}
			_minY = _maxY - _view.height + _originHeight - 10;
			_view.hitarea.height = _view.height;
			
			if(_view.hitarea.height <= 289) view.removeEventListener(MouseEvent.MOUSE_WHEEL, onMouseWheel);
			else view.addEventListener(MouseEvent.MOUSE_WHEEL, onMouseWheel);
			
			dispatchEvent(new MeasurementEvent(MeasurementEvent.HEIGHT_MEASUREMENT, view.height));
		}
		
		private function onClick(data:GalleryData):void
		{
			_callback(data);		
		}
		
		private function onMouseWheel(e:MouseEvent):void
		{
			dispatchEvent(e);
		}
	
	}
}